//
//  LivePhotoTools.swift
//  GifUsage
//
//  Created by han on 2021/1/5.
//  Copyright © 2021 Ting Han. All rights reserved.
//

import UIKit
import Photos

struct LivePhotoTools {
    // LivePhoto包含两个部分，一部分是一张jpg图片，一部分则是一个mov视频
    
    /// 保存本地LivePhoto到相册
    static func saveLivePhotoToAlbum(_ photoPath: String, _ videoPath: String) {
        // LivePhoto包含两个部分，一部分是一张jpg图片，一部分则是一个mov视频
        let photoURL = URL(fileURLWithPath: photoPath) // .jpg
        let videoURL = URL(fileURLWithPath: videoPath) // .mov
        
        PHPhotoLibrary.shared().performChanges {
            let request = PHAssetCreationRequest()
            request.addResource(with: .photo, fileURL: photoURL, options: nil)
            request.addResource(with: .pairedVideo, fileURL: videoURL, options: nil)
        } completionHandler: { (success, error) in
            if success {
                print("save livePhoto success")
            } else {
                print("save livePhoto error: \(String(describing: error))")
            }
        }

    }
    
    /// 显示相册中LivePhoto
    static func displayLivePhoto(asset: PHAsset) {
        let options = PHLivePhotoRequestOptions()
        options.deliveryMode = .highQualityFormat
        options.isNetworkAccessAllowed = true
        options.progressHandler = { progress, _, _, _ in
            print(progress)
        }
        PHImageManager.default().requestLivePhoto(for: asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .aspectFit, options: options) { (livePhoto, info) in
            guard let livePhoto = livePhoto else { return }
        }
    }
    
    /// 显示本地LivePhoto
    static func displayLivePhoto(_ photoPath: String, _ videoPath: String) {
//        URL(fileURLWithPath: Bundle.main.path(forResource: "", ofType: "JPG")!)
//        URL(fileURLWithPath: Bundle.main.path(forResource: "", ofType: "mov")!)
        PHLivePhoto.request(withResourceFileURLs: [URL(fileURLWithPath: photoPath), URL(fileURLWithPath: videoPath)], placeholderImage: UIImage(named: ""), targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit) { (livePhoto, info) in
            guard let livePhoto = livePhoto else { return }
        }
    }
    
    static func saveLivePhotoMovie(_ livePhotoAsset: PHAsset, completion: ((Bool, String?) -> Void)? = nil) {
        let resources = PHAssetResource.assetResources(for: livePhotoAsset)
        var movieResource: PHAssetResource? = nil
        for resource in resources {
            if resource.type == .pairedVideo {
                movieResource = resource
                break
            }
        }
        guard let resource = movieResource else {
            completion?(false, nil)
            return
        }
        self.getMovieData(resource: resource, completion: completion)
    }
    
    static func getMovieData(resource: PHAssetResource, fileName: String = "video.mov", completion: ((Bool, String?) -> Void)? = nil) {
        let temp = NSTemporaryDirectory() as NSString
        let timeFormat = DateFormatter()
        timeFormat.dateFormat = "yyyyMMddHHmmss"
        let time = timeFormat.string(from: Date(timeIntervalSinceNow: 0))
        let filePath = temp.appendingPathComponent(time).appending(fileName)
        if FileManager.default.fileExists(atPath: filePath) {
            do {
                try FileManager.default.removeItem(atPath: filePath)
            } catch  {
                completion?(false, nil)
                return
            }
        }
        
        let movieURL = URL(fileURLWithPath: filePath)
        PHAssetResourceManager.default().writeData(for: resource, toFile: movieURL, options: nil) { (error) in
            if error != nil{
                completion?(false, filePath)
            } else {
                completion?(true, filePath)
            }
        }
    }
    
    static func saveLivePhotoImage(_ livePhotoAsset: PHAsset, completion: ((Bool, String?) -> Void)? = nil) {
        let resources = PHAssetResource.assetResources(for: livePhotoAsset)
        var movieResource: PHAssetResource? = nil
        for resource in resources {
            if resource.type == .photo {
                movieResource = resource
                break
            }
        }
        guard let resource = movieResource else {
            completion?(false, nil)
            return
        }
        self.getMovieData(resource: resource, fileName: "image.jpg",  completion: completion)
    }
    
    
    
    static func LivePhotoMaker(_ photoPath: String, _ videoPath: String) {
        let temp = NSTemporaryDirectory() as NSString
        let timeFormat = DateFormatter()
        timeFormat.dateFormat = "yyyyMMddHHmmss"
        let time = timeFormat.string(from: Date(timeIntervalSinceNow: 0))
        let photoDest = temp.appendingPathComponent(time).appending("image.jpg")
        let videoDest = temp.appendingPathComponent(time).appending("video.jpg")
        
        let imageData: Data = (UIImage(contentsOfFile: photoPath)?.jpegData(compressionQuality: 1.0))!
        do {
            try imageData.write(to: URL(fileURLWithPath: photoDest))
            
        } catch  {
            
        }
        
    }
  
}

